<?php
require_once "../../_inc/funct.xml2array.php";
$isReloadable = false;
require_once("../../../pers/inc.config.php");
require_once('../../_inc/inc.session.php');
require_once('../../_inc/funct.html.php');
require_once('../../_inc/funct.tabDati.php');
require_once('../../_inc/class.rglDocGen.php');

$sSql = "SELECT b.file_caricato, b.str_def_dati, b.id_set_dati, a.cod_fisc, a.rag_soc, b.data_rif "
	." FROM rgl_bilancio b "
	." LEFT JOIN rgl_azienda a ON b.id_azienda = a.id_azienda" 
	." WHERE b.id_bil = ".reqVarInt('id');
$objDB->query($sSql,'readBilOrig');
$acB = $objDB->fetch('readBilOrig');
if (!$acB) {
	die("id.bil. '$idBil' non trovato ");
}
$aDefDati = unsgzu($acB['str_def_dati']);
$aGeDati = getGerarcDefDati($aDefDati,1);

//die("<pre>".print_r($aCodFonte,1)."</pre>");
$aXml = xml2array(gzuncompress($acB['file_caricato']),array('withAttr'=>true));
//die(x2vPrint($aXml));

$aTag = array();
foreach(rglVx($aXml,'aXml','xbrl',0) as $tagX => $aX) {
	for($kX=0;$kX<99999;$kX++) {
		if (!isset($aX[$kX])) break;
		if (is_array($aX[$kX])) continue;
		$aTag[$tagX] = $aX[$kX];
	}
}

$sCsv = '"cod_dato";"descr";"valore";"cod_fonte"'."\r\n";

foreach($aGeDati as $codX => $aX) {
	scriviCsv($sCsv, $codX, $aX, $aTag, 0);
}
$sCsv .= '"";"";"";"TAG NON RACCORDATI"'."\r\n";
foreach($aTag as $tagX => $vX) {
	if (substr($vX,0,15) == '-- assegnato a ') continue;
	$sCsv .= '"";"";"'.$vX.'";"'.$tagX.'"'."\r\n";
}

headerDownLoad(strlen($sCsv),"xblr_racc.csv");
echo $sCsv;
exit();

function scriviCsv(&$sCsv, $codX, $aX, &$aTag, $liv) {
	$codFonteX = substr($aX['attr']['cod_fonte'],8);
	if (isset($aTag[$codFonteX])) {
		$sVal = $aTag[$codFonteX];
		$aTag[$codFonteX] = '-- assegnato a '.$codX.' --';
	} else {
		$sVal = '-- cod_fonte insesistente --';
	}
	$sCsv .= '"'.$codX.'";"'.str_repeat(' ', $liv*5)
		.str_replace('"',"'",$aX['attr']['descr']).'";"'
		.$sVal.'";"'.$aX['attr']['cod_fonte'].'"'."\r\n";
	foreach($aX['figli'] as $codY => $aY)  {
		scriviCsv($sCsv, $codY, $aY, $aTag, $liv+1);
	}
}

